from django import http
from django.conf import settings
from django.contrib.auth import login

from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View

from apps.oauth.models import OAuthQQUser
from utils.response_code import RETCODE
from QQLoginTool.QQtool import OAuthQQ
# 判断是否绑定
def is_bind_openid(openid, request):
    # 判断openid在不在表里边
    try:
        qq_user = OAuthQQUser.objects.get(openid=openid)
    except OAuthQQUser.DoesNotExist:
        # 如果openid没绑定美多商城用户
        context = {'openid': openid}
        return render(request, 'oauth_callback.html', context)
    else:
        # 如果openid已绑定美多商城用户
        qq_user = qq_user.user
        # 保持登录状态
        login(request, qq_user)
        # cookie保持用户名
        response = redirect(reverse('contents:index'))
        # 登录时用户名写入到cookie，有效期15天
        response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)
        # 重定向到首页
    return response


class QQOauthCallbackView(View):
    def get(self, request):
        # code
        code = request.GET.get('code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET, redirect_uri=settings.QQ_REDIRECT_URI)
        # acess---token
        token = oauth.get_access_token(code)
        # openid
        openid = oauth.get_open_id(token)
        # 判断是否绑定
        response = is_bind_openid(openid, request)


        return response


class QQLoginView(View):
    # QQ登陆网址
    def get(self, request):
        # 导包

        # 实例化对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=None)

        # 返回前端
        login_url = oauth.get_qq_url()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url':login_url})
